// pages/updatePassword/updatePassword.js
import {updatePassword} from "../../service/user";
import {logout} from "../../service/auth";

const validate = require('../../utils/validate')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    old_password:'',
    password:'',
    password_confirmation:'',
    error_old_password:'',
    error_password:'',
    error_password_confirmation:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },
  /**
   * 修改密码
   */
  updatePassword(){
    //表单验证
    const check = this.checkInput()
    if(!check) return

    const data = {
      old_password: this.data.old_password,
      password: this.data.password,
      password_confirmation:this.data.password_confirmation
    }

    updatePassword(data).then(()=>{
      logout().then(()=>{
        wx.removeStorageSync('access_token')
        wx.removeStorageSync('userInfo')
        wx.showToast({
          title:'修改成功',
          icon:'success'
        })
      })
      wx.redirectTo({
        url:'/pages/login/login'
      })
    })
  },
  /**
   * 验证用户输入的内容
   */
  checkInput(){
    const {old_password,password,password_confirmation} = this.data

    const checkOldPassword = validate.min(old_password,6)
    const checkPassword = validate.min(password,6)
    const checkPassWordConfirmation = validate.same(password,password_confirmation)

    //表单验证
    if(!checkOldPassword){
      this.setData({
        error_old_password: '密码最少为六个字符'
      })
    }else{
      this.setData({error_old_password: ''})
    }
    if(!checkPassword){
      this.setData({error_password: '密码最少六个字符'})
    }else{
      this.setData({error_password: ''})
    }
    if(!checkPassWordConfirmation){
      this.setData({error_password_confirmation: '两次输入的密码不一致'})
    }else{
      this.setData({error_password_confirmation: ''})
    }
    if(checkOldPassword && checkPassword && checkPassWordConfirmation) return true
    return false
  }

})